<?php


namespace app\project\admin;


use app\admin\controller\Admin;
use app\project\model\ProjectUuid;
use app\project\model\Config;
use app\project\model\Category;
use app\common\builder\ZBuilder;
use app\project\model\Project;
use app\user\model\User;

/**
 * 项目表
 * Class Index
 * @package app\project\admin
 */
class Index extends Admin
{
    protected $user;
    protected $where = true;
    public function initialize()
    {
        parent::initialize();
        $this->user = session('user_auth');
        if ($this->user['role']==2){
            $this->where = ['principal'=>UID];
        }elseif ($this->user['role']==3){
            $this->where = ['team'=>UID];
        }
        $this->model = new Project();
    }

    /**
     * 当前权限
     * @return mixed
     * @throws \think\Exception
     */
    public function index(){
        $map = $this->getMap();
        if ($map){
            foreach ($map as &$value){
                if ($value[0] == 'principal_name'){
                    $info = User::where('username', '=', $value[2])->find();
                    $value[0]='principal';
                    $value[2]=$info['id'];
                }elseif ($value[0] == 'team_name'){
                    $info = User::where('username', '=', $value[2])->find();
                    $value[0]='team';
                    $value[2]=$info['id'];
                }
            }
        }
        $data = $this->model->with(['principalUser','teamUser','category'])->where($this->where)->select();

        $btn_execl = [
            'title' => '导出',
            'icon'  => 'fa fa-fw fa-key',
            'class' => 'btn btn-primary js-get',
            'href'  => url('',['excel'=>1])
        ];
        $btn_del = [
            'title' => '删除',
            'icon'  => 'fa fa-times',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href'  => url('del', ['id' => '__id__']),
            'data-title'=>'真的要删除吗?'
        ];
        $show_one= [
            'title'=>'待审核',
            'icon'=>'fa fa-fw fa-eye',
            'href'=>url('status',['id'=>'__id__']),
        ];


        return ZBuilder::make('table')
            ->addColumns([
                ['project_uuid', '项目号'],
                ['project_title', '项目名'],
                ['category_name', '项目分类'],
                ['principal_name', '项目负责人'],
                ['team_name', '团队负责人'],
                ['type', '类别',['教学','科研','人才经费']],
                ['money', '金额'],
                ['status', '审核状态', 'status','',['待负责人审核:info','待总负责人审核:primary','已通过:success']],
                ['start_time', '开始时间', 'datetime',],
                ['end_time', '结束时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add', [],true)
            ->addTopButton('execl', $btn_execl)
            ->addRightButton('del',$btn_del)
            ->addRightButton('show',$show_one,true)
            ->setRowList($data)
            ->setSearchArea([
                ['text', 'project_title', '项目名','like'],
                ['daterange', 'start_time', '项目开始时间'],
                ['daterange', 'end_time', '项目结束时间'],
                ['daterange', 'create_time', '项目申请时间'],
                ['text', 'principal_name', '项目负责人'],
                ['text', 'team_name', '团队负责人'],
                ['select', 'category_id', '项目分类','','',Category::column('id,title')],
            ])
            ->fetch();
    }

    public function add()
    {

        if($this->request->isPost()){
            $data = $this->request->post('', null, 'trim');
            $result = $this->validate($data, 'Project');
            if (true !== $result) {
                $this->error($result);
            }
            $config = Config::column('value','key');
            $json = [];
            foreach ($config as $key=>$value){
                if (in_array($key,array_keys($this->request->post()))){
                    if ($data[$key]>$value){
                        $this->error('报销比例不能超过规定值');
                    }elseif ($data[$key] ==0) {
                        unset($data[$key]);
                    }else{
                        $json[$key] = $data[$key];
                        unset($data[$key]);
                    }
                }
            }
            if (empty($json)){
                $this->error('请上传项目资金报销比例');
            }
            $insert = [
                'project_title'=>$data['project_title'],
                'project_uuid'=>$data['project_uuid'],
                'category_id'=>$data['category_id'],
                'principal'=>$data['principal'],
                'team'=>$data['team'],
                'type'=>$data['type'],
                'cause'=>$data['cause'],
                'money'=>$data['money'],
                'start_time'=>strtotime($data['start_time']),
                'end_time'=>strtotime($data['end_time']),
                'create_time'=>time(),
                'config'=>json_encode($json)
            ];
            if ($info = $this->model->create($insert)){
                $details = UID . '操作project_add,id为' . $info['id'];
                action_log('project_add', 'project', $info['id'], UID, $details);
                $this->success('新增成功','index',['_parent_reload'=>1,'_close_pop'=>1]);
            }
            $this->error('新增失败');
        }
        $jichu = [
            ['text', 'project_title', '项目名','项目名称请输入全程'],
            ['select', 'project_uuid', '项目号','请选择项目的项目号',ProjectUuid::column('project_uuid')],
            ['select', 'category_id', '分类','请选择项目分类',Category::column('id,title')],
            ['select', 'principal', '项目负责人', '请选择当前项目负责人', User::where('role', '=', 2)->column('id,username')],
            ['select', 'team', '团队负责人', '请选择当前项目负责人', User::where('role', '=', 3)->column('id,username'),UID],
            ['radio', 'type', '类别', '请选择当前项目类别',['教学','科研','人才经费等']],
            ['textarea', 'cause', '事由', '请说明项目事由'],
            ['daterange', 'start_time,end_time', '项目预计时间','输入项目预计实行的时间'],
        ];
        $zijin = [
            ['number', 'money', '金额(万元)', '这里输入项目金额'],
        ];
        $config = Config::select();
        foreach ($config as $value){
            $zijin[] = ['number',$value['key'],$value['title'],'没有的不填写,最多配置'.$value['value'].',即:'.$value['value'].'%',0];
        }
        return ZBuilder::make('form')
            ->setPageTips('信息提交后无法修改','danger')
            ->addFormItems([
                [
                    'type' => 'group',
                    'options' => [
                        '基本信息'=>$jichu,
                        '资金信息'=>$zijin
                    ]
                ]
            ])
            ->submitConfirm()
            ->fetch();
    }

    /**
     * 这里删除只能删除未审核的，且为本人提交的，所以不存在批量删除
     * 这里需要验证状态
     * @param int $id
     */
    public function del($id = 0)
    {
        $info = $this->model->find($id);
        if (!$info){
            $this->error('数据不存在');
        }
        $this->role($info);
        if ($info['status']!=0){
            $this->error('只有未审核的项目才可删除');
        }
        $this->model->destroy($id);
        $this->success('删除成功');
    }

    /**
     * 这里需要分辨有什么权限
     * @param int $id
     * @return mixed
     * @throws \think\Exception
     */
    public function status($id = 0)
    {
        $info = $this->model->with(['principalUser','teamUser'])->find($id);
        if (!$info){
            $this->error('数据不存在');
        }
        if($this->request->isPost()){
            if ($info['status']==0){//需要项目人负责人审核
                $update = [
                    'status'=>1,
                    'update_time'=>time()
                ];
            }elseif($info['status']==1&&$this->user['role']==1){//需要超管审核
                $update = [
                    'status'=>2,
                    'update_time'=>time()
                ];
            }elseif($info['status']==2){
                $this->error('无需审核');
            }else{
                $this->error('权限不足');
            }
            if ($info->save($update)){
                $details = UID . '操作project_status,id为' . $info['id'];
                action_log('project_status', 'project', $info['id'], UID, $details);
                $this->success('审核通过','index',['_parent_reload'=>1,'_close_pop'=>1]);
            }
            $this->error('审核失败');
        }
        $config = Config::column('title','key');
        $table_inside = [];
        $table_inside[] = ['类别', '比例(%)', '金额(万元)'];
        foreach ($info['config'] as $key=>$value){
            $table_inside[] = [$config[$key],$value,round($info['money']*$value/100,2)];
        }
        $table_inside[] = '4:1';       // 最后一个为字符串，用来设置所在单元格的合并，如果不需要合并则无需填写。
        $table_data = [
            ['项目名', $info['project_title'],'项目编号:'.$info['project_uuid'], '团队负责人(申请人):'.$info['team_name'], '项目负责人:'.$info['principal_name']],
            ['类别:'.$info['type'], '当前状态:'.$info['status'].'[2]', '开始时间:'.date('Y年m月d日',$info['start_time']), '预计结束时间:'.date('Y年m月d日',$info['end_time'])],
            ['项目申请资金:'.$info['money'].'万元', $table_inside],
            ['事由[:2]',$info['cause'].'[4:2]',],
        ];

        return ZBuilder::make('form')
            ->setPageTips('该页面用于审核和信息展示,审核可操作审核按钮')
            ->addFormItems([ // 批量添加表单项
                ['complexTable', 'list_user', '客户列表', $table_data]
            ])
            ->setBtnTitle('submit', '通过')
            ->hideBtn(['back'])
            ->addHidden('submit')
            ->fetch();
    }

    /**
     * 验证权限
     * @param $info当前操作数据
     */
    protected function role($info){
        if ($this->user['role']==2&&$this->user['uid']!=$info['principal']){
            $this->error('该操作权限不够');
        }
        if ($this->user['role']==3&&$this->user['uid']!=$info['team']){
            $this->error('该操作权限不够');
        }
    }
}